﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IceDog.Practice.WinForm.IceDogSocket
{
    public partial class FormSocketMain : Form
    {
        FormSocketMainCore core = new FormSocketMainCore();

        public FormSocketMain()
        {
            //用于允许跨线程调用
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            this.buttonConnect.Enabled = false;
            this.buttonSendServer.Enabled = false;
            this.buttonSendClient.Enabled = false;
            core.SetIPAndPort(labelTextBoxServerIP.PropValue, int.Parse(labelTextBoxServerPort.PropValue));
        }

        private void buttonStartListen_Click(object sender, EventArgs e)
        {
            core.SetIPAndPort(labelTextBoxServerIP.PropValue, int.Parse(labelTextBoxServerPort.PropValue));
            this.labelTextBoxServerIP.Enabled = false;
            this.labelTextBoxServerPort.Enabled = false;
            this.buttonConnect.Enabled = true;
            core.StartServerListen();
            this.textBoxServer.Text = "服务端(" + core.Server.LocalEndPoint.ToString() + ")进入监听状态，等待客户端连接中。。。\r\n";
            var t = new Thread(() =>
            {
                while (true)
                {
                    var accept = core.GetAcceptSocket();
                    this.buttonSendServer.Enabled = true;
                    this.textBoxServer.Text += "客户端" + accept.RemoteEndPoint.ToString() + "连接成功\r\n";
                    new Thread(() =>
                    {
                        while (true)
                        {
                            var receivedBytes = new byte[4096];
                            //会进入接受数据状态(即后续代码会暂停执行直到有接收到数据)，
                            //避免堵塞主线程，所以需要额外开启一个线程处理
                            var n = accept.Receive(receivedBytes);
                            var receivedStr = Encoding.UTF8.GetString(receivedBytes, 0, n);
                            var s = core.SockeDictServer[this.listBoxClientList.SelectedItem as string];
                            this.textBoxServer.Text += "服务端收到" + s.RemoteEndPoint.ToString() + "的信息：" + receivedStr + "\r\n";
                        }
                    }).Start();
                }
            });
            t.Start();
        }

        private void buttonSendServer_Click(object sender, EventArgs e)
        {
            var str = this.textBoxServerInput.Text;
            this.textBoxServerInput.Text = string.Empty;
            var data = Encoding.UTF8.GetBytes(str);
            var accept = core.SockeDictServer[(this.listBoxClientList.SelectedItem as string)];
            accept.Send(data, data.Length,System.Net.Sockets.SocketFlags.None);
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (this.listBoxClientList.Items.Count > 10)
            {
                MessageBox.Show("最多只能创建10个连接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var client = core.GetClientSocket();
            try
            {
                core.StartClientConnect(client);
                this.buttonSendClient.Enabled = true;
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                throw;
            }
            this.listBoxClientList.Items.Add(client.LocalEndPoint.ToString());
            this.listBoxClientList.SelectedItem = this.listBoxClientList.Items[this.listBoxClientList.Items.Count - 1];
            this.textBoxClient.Text = "客户端(" + client.LocalEndPoint.ToString() + ")连接服务端(" + client.RemoteEndPoint.ToString() + ")成功\r\n";
            var t = new Thread(() =>
            {
                while (true)
                {
                    var receivedBytes = new byte[4096];
                    //会进入接受数据状态(即后续代码会暂停执行直到有接收到数据)，
                    //避免堵塞主线程，所以需要额外开启一个线程处理
                    var n = client.Receive(receivedBytes);
                    var receivedStr = Encoding.UTF8.GetString(receivedBytes, 0, n);
                    var s = core.SockeDictClient[this.listBoxClientList.SelectedItem as string];
                    this.textBoxClient.Text += s.LocalEndPoint.ToString() + "收到的信息：" + receivedStr + "\r\n";
                }
            });
            t.Start();
        }

        private void buttonSendClient_Click(object sender, EventArgs e)
        {
            var str = this.textBoxClientInput.Text;
            this.textBoxClientInput.Text = string.Empty;
            var data = Encoding.UTF8.GetBytes(str);
            var accept = core.SockeDictClient[(this.listBoxClientList.SelectedItem as string)];
            accept.Send(data, data.Length, 0);
        }

        private void listBoxClientList_SelectedValueChanged(object sender, EventArgs e)
        {
            this.textBoxClient.Text += "切换到" + this.listBoxClientList.SelectedItem as string + "\r\n";
        }

        private void buttonClientCLose_Click(object sender, EventArgs e)
        {
            var p = this.listBoxClientList.SelectedItem as string;
            var s = core.SockeDictClient[p];
            s.Close();
            this.textBoxClient.Text += "客户端"+p+"监控已关闭\r\n";
        }

        private void buttonServerClose_Click(object sender, EventArgs e)
        {
            core.Server.Close();
            this.textBoxServer.Text += "服务端监控已关闭\r\n";
        }
    }
}
